package com.lianjia.analysis.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 跨域配置
 * 允许前端应用访问API
 */
@Configuration
public class CorsConfig {

    @Value("${cors.allowed-origins:*}")
    private String allowedOrigins;

    @Value("${cors.allowed-methods:GET,POST,PUT,DELETE}")
    private String allowedMethods;

    @Value("${cors.allowed-headers:*}")
    private String allowedHeaders;

    @Value("${cors.max-age:3600}")
    private long maxAge;

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        
        // 设置允许跨域的域名，如果允许所有域名则设置为"*"
        String[] origins = allowedOrigins.split(",");
        for (String origin : origins) {
            if ("*".equals(origin)) {
                // Spring Boot 3中，如果设置为"*"，则不能同时设置allowCredentials为true
                config.addAllowedOriginPattern(origin);
            } else {
                config.addAllowedOrigin(origin);
            }
        }
        
        // 设置允许的请求方法
        String[] methods = allowedMethods.split(",");
        for (String method : methods) {
            config.addAllowedMethod(method);
        }
        
        // 设置允许的请求头
        String[] headers = allowedHeaders.split(",");
        for (String header : headers) {
            config.addAllowedHeader(header);
        }
        
        // 设置是否允许发送Cookie
        // 注意：在Spring Boot 3中，如果设置为true，则不能使用通配符"*"作为允许的源
        if (!allowedOrigins.contains("*")) {
            config.setAllowCredentials(true);
        }
        
        // 设置预检请求的有效期，单位为秒
        config.setMaxAge(maxAge);
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        
        return new CorsFilter(source);
    }
}